package com.cking.wherehaveibeen;

<<<<<<< .mine
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
=======
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
>>>>>>> .r26
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.location.Location;
import android.os.Build;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class MyService extends IntentService {
	private GPSTracker gps;
	private double lat, lng;
	private PointDataSource pds;
	private List<Point> dayPoints;
	
	
    public MyService() {
    	super("name");
<<<<<<< .mine
=======
    	try {        	
        	String destPath = "/data/data/" + getPackageName() + "/databases/points.db";
        	File f = new File(destPath);        	
        	if (!f.exists()) {        	
			    CopyDB( getBaseContext().getAssets().open("mydb"), 
					new FileOutputStream(destPath));
        	}
		} catch (FileNotFoundException e) {			
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	pds = new PointDataSource(this);
>>>>>>> .r26
    	dayPoints = new ArrayList<Point>();
<<<<<<< .mine
    	boolean work = true;
    	
    	try{
    		String destPath = "/data/data/" + getPackageName() + "/databases/mydb";
        	File f = new File(destPath);        	
        	if (!f.exists()) {        	
			    CopyDB( getBaseContext().getAssets().open("mydb"), 
					new FileOutputStream(destPath));
        	}
        	pds = new PointDataSource(MyService.this);
			//pds.open();
    	}catch(Exception e){
    		work = false;
    		e.printStackTrace();
    	}finally{
    		if(work){
    			Dialog d = new Dialog(this);
    			d.setTitle("Yes");
    			d.show();
    		}
    	}
=======
    	pds.open();
>>>>>>> .r26
    }	

	@Override
	protected void onHandleIntent(Intent intent) {
		// TODO Auto-generated method stub
		double total = 0;
		gps = new GPSTracker(this);
		if(gps.canGetLocation){
			Location l = gps.getLocation();
			lat = l.getLatitude();
			lng = l.getLongitude();
			Calendar c = Calendar.getInstance();
			int day = c.get(Calendar.DAY_OF_MONTH);
			int month = c.get(Calendar.MONTH);
			int year = c.get(Calendar.YEAR);
			Point tmp = new Point();
			tmp.setDate(day + "-" + month + "-" + year);
			tmp.setPoint(lat+":"+lng);
			dayPoints.add(tmp);
		}else{
		}
		
        while(gps.canGetLocation){
        
			try {
				Thread.sleep(10000);
				Location l = gps.getLocation();
				double lat2 = l.getLatitude();
				double lng2 = l.getLongitude();
				double dist = calculateMovement(lat, lng, lat2, lng2);
				//We moved more than 50 yards and want to add the next point.
				if( total >= 50 || dist >= 50){
					addNotify(total, dist, lat2, lng2);
				}else{ // We have traveled less than 50 yards
					justNotify(total, dist);
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
        }


        Intent intents = new Intent(this, Splash.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intents, 0);
        Notification n  = new Notification.Builder(this)
     			        .setContentTitle("Whoever threw that paper ball...")
     			        .setContentText("Your mom is a hoe.")
     			        .setSmallIcon(R.drawable.ic_launcher)
     			        .setContentIntent(pIntent)
     			        .setAutoCancel(true).build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, n);
        pds.close();
	}
	
	@SuppressWarnings("unused")
	private boolean checkEnabled(GPSTracker gps) {
		// TODO Auto-generated method stub
    	// check if GPS enabled     
        if(gps.canGetLocation()){
            //double latitude = gps.getLatitude();
            //double longitude = gps.getLongitude();
            return true;
            // \n is for new line
            //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
        }else{
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            //gps.showSettingsAlert();
        	return false;
        }
	}
	

	@SuppressWarnings("unused")
	private double calculateMovement(double lat1, double lon1, double lat2, double lon2){
		double radlat1 = Math.PI * lat1/180;
		double radlat2 = Math.PI * lat2/180;
		double radlon1 = Math.PI * lon1/180;
		double radlon2 = Math.PI * lon2/180;
		double theta = lon1-lon2;
		double radtheta = Math.PI * theta/180;
		double dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
		dist = Math.acos(dist);
		dist = dist * 180/Math.PI;
		dist = dist * 60 * 1.1515;
		dist = dist * 1760;
		return dist;
	}

	private void addNotify(double total, double dist, double lat2, double lng2){
		lat = lat2;
		lng = lng2;
		Calendar c = Calendar.getInstance();
		int day = c.get(Calendar.DAY_OF_MONTH);
		int month = c.get(Calendar.MONTH);
		int year = c.get(Calendar.YEAR);
		Point tmp = new Point();
		tmp.setDate(day + "-" + month + "-" + year);
		tmp.setPoint(lat+":"+lng);
		dayPoints.add(tmp);
		//pds.createPoint(getAllPoints());
		
	    // prepare intent which is triggered if the notification is selected
		Intent intents = new Intent(this, Splash.class);
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intents, 0);
		// build notification
		Notification n  = new Notification.Builder(this)
		        .setContentTitle("You have traveled:")
		        .setContentText(dist + " yards")
		        .setSmallIcon(R.drawable.ic_launcher)
		        .setContentIntent(pIntent)
		        .setAutoCancel(true).build();
		  
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.notify(0, n);
		
	}
	
	@SuppressWarnings("unused")
	private void justNotify(double total, double dist){
		Calendar c = Calendar.getInstance();
		int day = c.get(Calendar.DAY_OF_MONTH);
		int month = c.get(Calendar.MONTH);
		int year = c.get(Calendar.YEAR);
		total = total + dist;
		Intent intents = new Intent(this, Splash.class);
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intents, 0);

		// build notification
		Notification n  = new Notification.Builder(this)
		        .setContentTitle(total + " yards:")
		        .setContentText(getAllPoints())
		        .setSmallIcon(R.drawable.ic_launcher)
		        .setContentIntent(pIntent)
		        .setAutoCancel(true).build();
		  
		NotificationManager notificationManager = 
		  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		notificationManager.notify(0, n);
		
	}
	
	private String getAllPoints(){
		String points = "";
		for(int i = 0; i < dayPoints.size()-1; i++){
			points += dayPoints.get(i).getPoint() + " ";
		}
		points += dayPoints.get(dayPoints.size()-1).getPoint();
		
		return points;
	}
	
<<<<<<< .mine
	public void CopyDB(InputStream inputStream, OutputStream outputStream) 
		    throws IOException {
		        //---copy 1K bytes at a time---
		        byte[] buffer = new byte[1024];
		        int length;
		        while ((length = inputStream.read(buffer)) > 0) {
		            outputStream.write(buffer, 0, length);
		        }
		        inputStream.close();
		        outputStream.close();
		    }
	
	
=======
	public void CopyDB(InputStream inputStream, OutputStream outputStream) 
		    throws IOException {
		        //---copy 1K bytes at a time---
		        byte[] buffer = new byte[1024];
		        int length;
		        while ((length = inputStream.read(buffer)) > 0) {
		            outputStream.write(buffer, 0, length);
		        }
		        inputStream.close();
		        outputStream.close();
		    }
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}
>>>>>>> .r26

}

